package org.smart4j.framework.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * json工具类（基于Jackson）
 * JSON->Pojo
 *
 * @author YooLin1c
 * @version 1.0.0
 * @since 2018-01-30 20:46
 */
@Slf4j
public final class JsonUtil {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 实体转JSON
     *
     * @param pojo 实体
     * @param <T>  实体泛型
     * @return JSON字符串
     */
    public static <T> String toJson(T pojo) {
        String json;
        try {
            json = OBJECT_MAPPER.writeValueAsString(pojo);
        } catch (JsonProcessingException e) {
            log.error("pojo : ".concat(pojo.toString()).concat(" to json failed!"), e);
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * JSON字符串转实体
     *
     * @param json JSON字符串
     * @param type 实体类型
     * @param <T>  实体泛型
     * @return 实体对象
     */
    public static <T> T toPojo(String json, Class<T> type) {
        T pojo;
        try {
            pojo = OBJECT_MAPPER.readValue(json, type);
        } catch (Exception e) {
            log.error("json : ".concat(json).concat(" to ".concat(type.getName()).concat(" failed!")), e);
            throw new RuntimeException(e);
        }
        return pojo;
    }
}
